import * as Bluebird from 'bluebird'
import * as redisLock from 'redis-lock'


export interface unlocker {
  (): void
}


export function createLock(redisClient: any) {
  const rawLock = redisLock(redisClient)

  const wrappedWithErrorFist = function (id, timeout, onLocked) {
    rawLock(id, timeout, function (done) {
      onLocked(null, done)
    })
  }

  const asyncLock = Bluebird.promisify<unlocker, string, number>(wrappedWithErrorFist)

  return async function lock(lockId: string, timeOutInMs: number = 5000): Promise<unlocker> {
    return asyncLock(lockId, timeOutInMs)
  }
}
